package cn.btks.zuulserver.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * @Author lijun
 * @Date 2021/1/9 16:39
 */
@Slf4j
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {

    /**
     *
     * @param authentication 包含了当前登录用户的角色信息
     * @param o
     * @param collection UrlFilterInvocationSecurityMetadataSource 中的 getAttributes 方法传来的，表示当前请求需要的角色（可能有多个）
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()){
            ConfigAttribute configAttribute = iterator.next();
            //请求该资源所需要的角色
            String needRole = configAttribute.getAttribute();
            log.info("needRole:" + needRole);
            /**如果当前请求需要的权限为 ROLE_LOGIN 则表示登录即可访问，和角色没有关系，
             此时需要判断判断 authentication 是不是 AnonymousAuthenticationToken 的一个实例，如果是，则表示当前用户没有登录，
             没有登录就抛一个 BadCredentialsException 异常，登录了就直接返回，则这个请求将被成功执行**/
            if("ROLE_LOGIN".equals(needRole)){
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new BadCredentialsException("未登录");
                }else {
                    throw new AccessDeniedException("权限不足!");
//                    return;
                }
            }
            //用户所包含的角色,只要有一个角色就允许通过
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities){
                if(authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
